package ch.zbw.pra.sysventory.domain.scanner;

import ch.zbw.pra.sysventory.domain.model.OperatingSystem;
import ch.zbw.pra.sysventory.domain.util.MyLogger;
import ch.zbw.pra.sysventory.ui.DetailLabel;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

public class ScanOperatingSystem {

	private static final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(ScanOperatingSystem.class);

	private OperatingSystem oSystem;

	// Constructor
	public ScanOperatingSystem() {

	}

	/*
	 * Read entrys from OS
	 */
	public OperatingSystem getOperatingSystem() {

		String host = "localhost";
		String connectStr = String.format("winmgmts:\\\\%s\\root\\CIMV2", host);
		String query = "SELECT * FROM Win32_OperatingSystem";
		try {
			// Load Library
			ActiveXComponent axWMI = new ActiveXComponent(connectStr);
			// Execute the query
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));

			// The Rusult is a Collection
			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;
			while (enumVariant.hasMoreElements()) {
				item = enumVariant.nextElement().toDispatch();
				// Dispatch.call returns a Variant which we can convert to a
				// java
				// form.
				String nameOperatingSystem = Dispatch.call(item, "Caption").toString();
				String buildOperatingSystem = Dispatch.call(item, "Version").toString();
				String architectureOperatingSystem = "NA";
				try {
					architectureOperatingSystem = Dispatch.call(item, "OSArchitecture").toString();
				} catch (Exception e) {
				}

				MyLogger.logDebug(log, nameOperatingSystem + " " + buildOperatingSystem + " "
						+ architectureOperatingSystem);
				DetailLabel.setTextDetailLabel(nameOperatingSystem);
				oSystem = new OperatingSystem(nameOperatingSystem, buildOperatingSystem,
						architectureOperatingSystem);
			}
		} catch (Exception e) {
			MyLogger.logError(log, e.toString());
		}

		return oSystem;
	}
}
